import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
// import store from '@/store'
// import {getToken, getRefreshToken} from '@/utils/auth'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 500000
})

service.interceptors.request.use(
  config => {
    // if (store.getters.token) {
    //   config.headers['token'] = 'Bearer ' + getToken()
    // }
    // config.headers['language'] = store.getters.language
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

let refreshing = false,// 正在刷新标识，避免重复刷新
  waitQueue = [] // 请求等待队列

service.interceptors.response.use(
  response => {
    const {code, msg, data} = response.data
    if (code !== '00000' && code !== '0' && code !== '1' &&code !== '2') {
      if (code === 'A0230') { // access_token过期 使用refresh_token换取access_token
        const config = response.config
        if (refreshing == false) {
          refreshing = true 
           
          
          
        } else {
          // 正在刷新token，返回未执行resolve的Promise,刷新token执行回调
          return new Promise((resolve => {
            waitQueue.push((token) => {
              config.headers['token'] = 'Bearer ' + token
              config.baseURL = '' // 请求重试时，url已包含baseURL
              resolve(service(config))
            })
          }))
        }
      } else if(code === 'A0210'){
        if(store.getters.language=='en'){
          Message({message: 'Wrong user name or password',type: 'error',duration: 5000})
        }else{
          Message({message: '用户名或密码错误',type: 'error',duration: 5000})
        }

      }else {
        Message({
          message: msg || '系统出错',
          type: 'error',
          duration: 5 * 1000
        })
      }
    }
    return {code, msg, data}
  },
  error => {
    return Promise.reject(error)
  }
)
export default service
